/**
 * 
 */
package u.can.i.up.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 
 * @author lczgywzyy
 * @date 2012-12-20 下午5:25:31
 * 
 */
public class StringUtils {

	public static boolean isEmpty(String input) {
		if (input == null || input.length() == 0) {
			return true;
		} else {
			return false;
		}
	}

	public static String byteArrayToHexString(byte[] byteArray) {
		StringBuilder sbuilder = new StringBuilder();
		for (int i = 0; i < byteArray.length; i++) {
			String hex = Integer.toHexString(0xff & byteArray[i]);
			if (hex.length() == 1) {
				sbuilder.append('0');
			}
			sbuilder.append(hex);
		}
		return sbuilder.toString();
	}

	public static String md5Encode(String rawString) throws UnsupportedEncodingException, NoSuchAlgorithmException {
		byte[] rawBytes;
		rawBytes = rawString.getBytes("UTF-8");
		if (rawBytes == null | rawBytes.length == 0) {
			rawBytes = rawString.getBytes();
		}
		MessageDigest messageDigest;
		messageDigest = MessageDigest.getInstance("MD5");
		String output = byteArrayToHexString(messageDigest.digest(rawBytes));
		return output;
	}

	/**
	 * @author lczgywzyy
	 * @param targetStr
	 *            目标字符串;
	 * @param part
	 *            规则字符;
	 * @return 返回计数器值.
	 */
	public static int countStr(String targetStr, String part) {
		return countStr(targetStr, part, 0);
	}

	private static int countStr(String targetStr, String part, int counter) {
		if (targetStr.indexOf(part) == -1) {
			return counter;
		} else {
			counter++;
			return countStr(targetStr.substring(targetStr.indexOf(part) + part.length()), part, counter);
		}
	}

	/**
	 * @author lczgywzyy
	 * @param targetStr
	 *            目标字符串;
	 * @param part
	 *            规则字符;
	 * @param filterCnt
	 *            过滤器, part出现次数;
	 * @return 返回经过滤器筛选后的字符串.
	 */
	public static String splitPartStr(String targetStr, String part, int filterCnt) {
		String tmpStr = targetStr;
		if (filterCnt >= 0) {
			while (countStr(tmpStr, part, 0) >= filterCnt) {
				tmpStr = tmpStr.substring(0, tmpStr.lastIndexOf(part));
			}
		}
		return tmpStr;
	}
}
